<template>
  <div>
    <el-card>
      <template #header>
        <h2>膳食配置</h2>
      </template>

      <!-- 搜索区 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="客户姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="客户姓名"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="openDrawer">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区 -->
      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%; margin-top: 12px"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column label="性别" width="80">
          <template #default="{ row }">
            {{ row.customerSex === 0 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="customerAge" label="年龄" width="60" />
        <el-table-column prop="preference" label="喜好" />
        <el-table-column prop="notes" label="注意事项" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="edit(row)">修改</el-button>
            <el-button size="small" type="danger" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <el-pagination
        style="margin-top: 12px; text-align: right;"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10,20,50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="loadData"
        @size-change="loadData"
      />
    </el-card>

    <!-- 新增/修改抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      size="40%"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="客户姓名" prop="customerId" required>
          <el-select v-model="form.customerId" placeholder="请选择客户">
            <el-option
              v-for="cust in customers"
              :key="cust.id"
              :label="cust.name"
              :value="cust.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-input :value="currentSexLabel" disabled />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input :value="form.customerAge" disabled />
        </el-form-item>
        <el-form-item label="喜好" prop="preference">
          <el-input v-model="form.preference" placeholder="请输入喜好" />
        </el-form-item>
        <el-form-item label="注意事项" prop="notes">
          <el-input v-model="form.notes" placeholder="请输入注意事项" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">
            {{ drawerTitle }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, inject, watch, onMounted, computed } from 'vue'
import qs from 'qs'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

// 注入 axios
const axios = inject('axios')

// 分页 & 搜索
const searchForm = reactive({ name: '' })
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表格数据
const tableData = ref([])

// 抽屉表单状态
const drawerVisible = ref(false)
const drawerTitle = ref('')
const form = reactive({
  id: 0,
  customerId: null,
  customerName: '',
  customerSex: 0,
  customerAge: 0,
  preference: '',
  notes: '',
  remark: ''
})

// 下拉客户列表
const customers = ref([])

// 根据选中的 customerId 自动填充客户信息
watch(() => form.customerId, async id => {
  if (id != null) {
    try {
      const resp = await axios.get(
        'CustomerController/getById',
        { params: { id } }
      )
      const rb = resp.data
      if (rb.status === 200 && rb.data) {
        const c = rb.data
        form.customerName = c.name
        form.customerSex = c.gender
        form.customerAge = Math.floor(
          (Date.now() - new Date(c.birthDate)) / (1000 * 3600 * 24 * 365)
        )
      } else {
        form.customerName = ''
        form.customerSex = 0
        form.customerAge = 0
        ElMessage.warning('未找到该客户')
      }
    } catch (err) {
      console.error(err)
      ElMessage.error('拉取客户信息失败')
    }
  } else {
    form.customerName = ''
    form.customerSex = 0
    form.customerAge = 0
  }
})

// 性别标签
const currentSexLabel = computed(() =>
  form.customerSex === 0 ? '男' : '女'
)

// 加载客户下拉
async function loadCustomers() {
  // 默认拉所有客户，也可加分页/类型筛选
  const resp = await axios.post(
    'CustomerController/queryAll',
    qs.stringify({ cur: 1, number: 1000, name: '',type:0 })
  )
  if (resp.data.status === 200) {
    customers.value = resp.data.data
  }
}

// 加载表格
async function loadData() {
  const resp = await axios.post(
    'MealManagementController/queryMealManagementByName',
    qs.stringify({
      name: searchForm.name,
      cur: currentPage.value,
      number: pageSize.value
    })
  )
  const rb = resp.data
  if (rb.status === 200) {
    const list = rb.data
    total.value = rb.total

    // 批量取出 customerId 列表
    const ids = [...new Set(list.map(m => m.customerId))]
    let id2info = {}
    if (ids.length) {
      const cre = await axios.post(
        'CustomerController/batchByIds',
        qs.stringify({ ids }, { arrayFormat: 'repeat' }),
      )
      if (cre.data.status === 200) {
        id2info = cre.data.data.reduce((m,c)=> (m[c.id]=c, m), {})
      }
    }

    tableData.value = list.map(m => ({
      ...m,
      customerName: id2info[m.customerId]?.name || '',
      customerSex: id2info[m.customerId]?.gender ?? 0,
      customerAge: id2info[m.customerId]
        ? Math.floor((Date.now() - new Date(id2info[m.customerId].birthDate)) / (1000*3600*24*365))
        : 0
    }))
  } else {
    tableData.value = []
    total.value = 0
    ElMessage.warning('暂无数据')
  }
}

// 打开新增
function openDrawer() {
  drawerTitle.value = '新增膳食配置'
  Object.assign(form, {
    id: 0,
    customerId: null,
    customerName: '',
    customerSex: 0,
    customerAge: 0,
    preference: '',
    notes: '',
    remark: ''
  })
  loadCustomers()
  drawerVisible.value = true
}

// 编辑
function edit(row) {
  drawerTitle.value = '修改膳食配置'
  Object.assign(form, row)
  loadCustomers()
  drawerVisible.value = true
}

// 删除
async function remove(id) {
  const resp = await axios.post(
    'MealManagementController/deleteMealManagement',
    qs.stringify({ id })
  )
  if (resp.data.status === 200) {
    ElMessage.success('删除成功')
    loadData()
  } else {
    ElMessage.error('删除失败：' + resp.data.message)
  }
}

// 提交
async function submit() {
  const api = form.id
    ? 'MealManagementController/updateMealManagement'
    : 'MealManagementController/addMealManagement'
  // 从 form 中剔除只读字段
  const payload = {
    id: form.id,
    customerId: form.customerId,
    preference: form.preference,
    notes: form.notes,
    remark: form.remark
  }
  const resp = await axios.post(api, qs.stringify(payload))
  if (resp.data.status === 200) {
    ElMessage.success(drawerTitle.value + '成功')
    drawerVisible.value = false
    loadData()
  } else {
    ElMessage.error(drawerTitle.value + '失败：' + resp.data.message)
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.el-form-item {
  margin-right: 16px;
}
</style>
